Page({
  data: {
    currentDate: '',
    classList: [
      { id: 0, name: '全部班级' },
      { id: 1, name: '2023级计算机科学1班' },
      { id: 2, name: '2023级软件工程1班' },
      { id: 3, name: '2022级数据科学1班' }
    ],
    classIndex: 0,
    statusList: ['全部', '已签到', '迟到', '请假', '缺勤'],
    statusIndex: 0,
    attendanceList: [],
    attendanceStats: {
      total: 0,
      checkedIn: 0,
      late: 0,
      absent: 0
    },
    isLoading: false,
    showStatusModal: false,
    currentStudent: {},
    selectedStatus: '',
    checkInTime: '08:00',
    remarks: ''
  },

  onLoad: function() {
    // 设置当前日期
    const today = new Date();
    const year = today.getFullYear();
    const month = String(today.getMonth() + 1).padStart(2, '0');
    const day = String(today.getDate()).padStart(2, '0');
    
    this.setData({
      currentDate: `${year}-${month}-${day}`
    });
    
    this.fetchAttendanceList();
  },
  
  onShow: function() {
    // 页面显示时刷新数据
    this.fetchAttendanceList();
  },
  
  // 日期变更
  dateChange: function(e) {
    this.setData({
      currentDate: e.detail.value,
      attendanceList: []
    });
    
    this.fetchAttendanceList();
  },
  
  // 班级变更
  classChange: function(e) {
    this.setData({
      classIndex: e.detail.value,
      attendanceList: []
    });
    
    this.fetchAttendanceList();
  },
  
  // 状态变更
  statusChange: function(e) {
    this.setData({
      statusIndex: e.detail.value,
      attendanceList: []
    });
    
    this.fetchAttendanceList();
  },
  
  // 获取考勤列表
  fetchAttendanceList: function() {
    if (this.data.isLoading) return;
    
    this.setData({ isLoading: true });
    
    const classId = this.data.classList[this.data.classIndex].id;
    const status = this.data.statusList[this.data.statusIndex];
    
    wx.request({
      url: 'http://localhost:3000/api/counselor/attendance',
      method: 'GET',
      data: {
        date: this.data.currentDate,
        classId: classId === 0 ? '' : classId,
        status: status === '全部' ? '' : status
      },
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        if (res.statusCode === 200) {
          this.setData({
            attendanceList: res.data.records,
            attendanceStats: res.data.stats
          });
        }
      },
      fail: () => {
        // 使用模拟数据
        const mockAttendance = [
          { id: 1, studentName: '张三', studentId: '2023001', checkInTime: '08:05', status: '已签到', remarks: '' },
          { id: 2, studentName: '李四', studentId: '2023002', checkInTime: '08:32', status: '迟到', remarks: '堵车' },
          { id: 3, studentName: '王五', studentId: '2023003', checkInTime: '', status: '请假', remarks: '生病' },
          { id: 4, studentName: '赵六', studentId: '2023004', checkInTime: '', status: '缺勤', remarks: '' },
          { id: 5, studentName: '钱七', studentId: '2022001', checkInTime: '08:15', status: '已签到', remarks: '' }
        ];
        
        // 根据筛选条件过滤
        let filteredAttendance = [...mockAttendance];
        
        if (this.data.classIndex !== 0) {
          // 模拟班级筛选，实际应该根据班级ID筛选
          if (this.data.classIndex === 1) {
            filteredAttendance = filteredAttendance.filter(item => ['2023001', '2023002'].includes(item.studentId));
          } else if (this.data.classIndex === 2) {
            filteredAttendance = filteredAttendance.filter(item => ['2023003', '2023004'].includes(item.studentId));
          } else if (this.data.classIndex === 3) {
            filteredAttendance = filteredAttendance.filter(item => ['2022001'].includes(item.studentId));
          }
        }
        
        if (this.data.statusIndex !== 0) {
          const status = this.data.statusList[this.data.statusIndex];
          filteredAttendance = filteredAttendance.filter(item => item.status === status);
        }
        
        // 计算统计数据
        const stats = {
          total: filteredAttendance.length,
          checkedIn: filteredAttendance.filter(item => item.status === '已签到').length,
          late: filteredAttendance.filter(item => item.status === '迟到').length,
          absent: filteredAttendance.filter(item => item.status === '缺勤').length
        };
        
        this.setData({
          attendanceList: filteredAttendance,
          attendanceStats: stats
        });
      },
      complete: () => {
        this.setData({ isLoading: false });
        wx.stopPullDownRefresh();
      }
    });
  },
  
  // 修改考勤状态
  updateStatus: function(e) {
    const id = e.currentTarget.dataset.id;
    const status = e.currentTarget.dataset.status;
    
    // 查找当前学生
    const student = this.data.attendanceList.find(item => item.id === id);
    
    if (student) {
      this.setData({
        showStatusModal: true,
        currentStudent: student,
        selectedStatus: status,
        checkInTime: student.checkInTime || '08:00',
        remarks: student.remarks || ''
      });
    }
  },
  
  // 选择状态
  selectStatus: function(e) {
    this.setData({
      selectedStatus: e.currentTarget.dataset.status
    });
  },
  
  // 时间变更
  timeChange: function(e) {
    this.setData({
      checkInTime: e.detail.value
    });
  },
  
  // 备注输入
  remarksInput: function(e) {
    this.setData({
      remarks: e.detail.value
    });
  },
  
  // 关闭弹窗
  closeModal: function() {
    this.setData({
      showStatusModal: false
    });
  },
  
  // 确认修改状态
  confirmStatusUpdate: function() {
    const student = this.data.currentStudent;
    
    wx.showLoading({
      title: '提交中...',
    });
    
    wx.request({
      url: `http://localhost:3000/api/counselor/attendance/${student.id}`,
      method: 'PUT',
      data: {
        status: this.data.selectedStatus,
        checkInTime: this.data.selectedStatus === '已签到' || this.data.selectedStatus === '迟到' ? this.data.checkInTime : '',
        remarks: this.data.remarks,
        date: this.data.currentDate
      },
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        wx.hideLoading();
        
        if (res.statusCode === 200) {
          wx.showToast({
            title: '修改成功',
            icon: 'success'
          });
          
          this.closeModal();
          this.fetchAttendanceList();
        } else {
          wx.showToast({
            title: res.data.message || '修改失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.hideLoading();
        
        // 模拟成功
        wx.showToast({
          title: '修改成功',
          icon: 'success'
        });
        
        // 更新本地数据
        const newList = this.data.attendanceList.map(item => {
          if (item.id === student.id) {
            return {
              ...item,
              status: this.data.selectedStatus,
              checkInTime: this.data.selectedStatus === '已签到' || this.data.selectedStatus === '迟到' ? this.data.checkInTime : '',
              remarks: this.data.remarks
            };
          }
          return item;
        });
        
        // 重新计算统计数据
        const stats = {
          total: newList.length,
          checkedIn: newList.filter(item => item.status === '已签到').length,
          late: newList.filter(item => item.status === '迟到').length,
          absent: newList.filter(item => item.status === '缺勤').length
        };
        
        this.setData({
          attendanceList: newList,
          attendanceStats: stats
        });
        
        this.closeModal();
      }
    });
  },
  
  // 一键签到
  checkAllIn: function() {
    wx.showModal({
      title: '确认操作',
      content: '确定要将所有未签到的学生标记为已签到吗？',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: '处理中...',
          });
          
          wx.request({
            url: 'http://localhost:3000/api/counselor/attendance/check-all',
            method: 'POST',
            data: {
              date: this.data.currentDate,
              classId: this.data.classList[this.data.classIndex].id === 0 ? '' : this.data.classList[this.data.classIndex].id
            },
            header: {
              'Authorization': 'Bearer ' + wx.getStorageSync('token')
            },
            success: (res) => {
              wx.hideLoading();
              
              if (res.statusCode === 200) {
                wx.showToast({
                  title: '操作成功',
                  icon: 'success'
                });
                
                this.fetchAttendanceList();
              } else {
                wx.showToast({
                  title: res.data.message || '操作失败',
                  icon: 'none'
                });
              }
            },
            fail: () => {
              wx.hideLoading();
              
              // 模拟成功
              wx.showToast({
                title: '操作成功',
                icon: 'success'
              });
              
              // 更新本地数据
              const newList = this.data.attendanceList.map(item => {
                if (item.status === '缺勤') {
                  return {
                    ...item,
                    status: '已签到',
                    checkInTime: '08:00'
                  };
                }
                return item;
              });
              
              // 重新计算统计数据
              const stats = {
                total: newList.length,
                checkedIn: newList.filter(item => item.status === '已签到').length,
                late: newList.filter(item => item.status === '迟到').length,
                absent: newList.filter(item => item.status === '缺勤').length
              };
              
              this.setData({
                attendanceList: newList,
                attendanceStats: stats
              });
            }
          });
        }
      }
    });
  },
  
  // 导出考勤记录
  exportAttendance: function() {
    wx.showLoading({
      title: '导出中...',
    });
    
    const classId = this.data.classList[this.data.classIndex].id;
    const status = this.data.statusList[this.data.statusIndex];
    
    wx.request({
      url: 'http://localhost:3000/api/counselor/attendance/export',
      method: 'POST',
      data: {
        date: this.data.currentDate,
        classId: classId === 0 ? '' : classId,
        status: status === '全部' ? '' : status
      },
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        wx.hideLoading();
        
        if (res.statusCode === 200) {
          wx.showModal({
            title: '导出成功',
            content: '考勤记录已导出，请到系统后台下载',
            showCancel: false
          });
        } else {
          wx.showToast({
            title: res.data.message || '导出失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.hideLoading();
        
        // 模拟成功
        wx.showModal({
          title: '导出成功',
          content: '考勤记录已导出，请到系统后台下载',
          showCancel: false
        });
      }
    });
  },
  
  // 查看考勤统计
  viewStatistics: function() {
    wx.navigateTo({
      url: '/pages/counselor/kaoqin/statistics/statistics'
    });
  },
  
  // 下拉刷新
  onPullDownRefresh: function() {
    this.fetchAttendanceList();
  }
})